package com.ynet.hmds28.service.mq;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.Producer;
import com.aliyun.openservices.ons.api.SendResult;
import com.aliyun.openservices.ons.api.exception.ONSClientException;
import com.taobao.middleware.logger.Logger;
import com.taobao.middleware.logger.LoggerFactory;

@Component
public class AliMQUtil {
    private static final Logger logger = LoggerFactory.getLogger(AliMQUtil.class);

    @Autowired
    private AliMQConfig aliMQConfig;

    // 发送消息
    public void sendMessage(String topic,String tag, String key, byte[] body) {
        Producer producer = aliMQConfig.getProducer();
        Message msg = new Message(topic, tag, body);
        msg.setKey(key);
        try {
            SendResult sendResult = producer.send(msg);
            if (sendResult != null) {
                logger.info("消息发送成功：" + sendResult.toString());
            }
        } catch (ONSClientException e) {
            logger.info("消息发送失败：", e);
            // 出现异常意味着发送失败，为了避免消息丢失，建议缓存该消息然后进行重试。
        }
    }
}
